package com.tm.car.service.impl;

import com.tm.car.pojo.User;
import com.tm.car.pojo.dto.LoginRequest;
import com.tm.car.pojo.dto.LoginResponse;
import com.tm.car.service.UserService;
import com.tm.car.utils.JwtUtil;
import com.tm.car.utils.Md5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import java.time.LocalDateTime;

@Service
public abstract class UserServiceImpl implements UserService {

    @PersistenceContext
    private EntityManager entityManager;

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public User findByUsername(String username) {
        try {
            return entityManager.createQuery(
                    "SELECT u FROM User u WHERE u.username = :identifier OR u.phone = :identifier", 
                    User.class)
                    .setParameter("identifier", username)
                    .getSingleResult();
        } catch (NoResultException e) {
            return null;
        }
    }

    @Override
    @Transactional
    public LoginResponse login(LoginRequest loginRequest) {
        // 查找用户（支持用户名或手机号登录）
        User user = findByUsername(loginRequest.getUsername());
        if (user == null) {
            throw new UsernameNotFoundException("用户不存在");
        }

        // 验证用户状态
        if (user.getIsValid() != null && user.getIsValid() != 1) {
            throw new BadCredentialsException("账号已被禁用");
        }

        // 验证密码
        String encodedPassword = Md5Util.encode(loginRequest.getPassword());
        if (!user.getPassword().equals(encodedPassword)) {
            throw new BadCredentialsException("密码错误");
        }

        // 更新最后登录时间
        user.setLastLoginTime(LocalDateTime.now());
        entityManager.merge(user);

        // 生成JWT令牌
        String token = jwtUtil.generateToken(user.getUsername());

        // 构建并返回登录响应
        return LoginResponse.builder()
                .token(token)
                .userId(user.getId())
                .username(user.getUsername())
                .name(user.getName())
                .phone(user.getPhone())
                .lastLoginTime(user.getLastLoginTime())
                .build();
    }
}
